package com.zishuimuyu.config;

import com.zishuimuyu.mqtt.MyMqttCallback;
import com.zishuimuyu.mqtt.MyMqttClient;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class MqttClientConfig {

    @Bean
    public MyMqttClient myMqttClient(MyMqttCallback myMqttCallback, MqttConfig mqttConfig) {
        MyMqttClient client = new MyMqttClient();
        client.setMyMqttCallback(myMqttCallback);
        try {
            client.connect(
                mqttConfig.getUrls(),
                mqttConfig.getUsername(),
                mqttConfig.getPassword(),
                mqttConfig.getClientId(),
                mqttConfig.getWillTopic(),
                mqttConfig.getWillContent(),
                mqttConfig.getCompletionTimeout(),
                mqttConfig.getKeepAliveInterval(),
                mqttConfig.getDataTopic()
            );
        } catch (MqttException e) {
            log.error("mqtt connect error: {}", e.getMessage());
        }
        return client;
    }
}
